/*
	Copyright 2007-2010 Petr Ohlidal

	This file is a part of GrobMaker

	GrobMaker is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	GrobMaker is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with GrobMaker.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "PegFileList.hpp"
#include "../InputData.hpp"
#include "../Images/Image.hpp"
#include "../Util/FileList.hpp"

namespace GrobMaker{

bool PegFileList::sortPegFileListsByPegIndex( const PegFileList& a, const PegFileList& b ){
	return a.pegIndex > b.pegIndex;
}

bool PegFileList::checkPegsDir(const fs::path& dir, const std::list<FileInfo>& files, InputData& inputData){
	// If there are at least noVisualAngles files, it may be a pegs dir
	if(static_cast<int>(files.size())>=inputData.noAngles){
		std::list<FileInfo> images;
		// List all images
		for( std::list<FileInfo>::const_iterator it=files.begin(); it!=files.end(); it++ ){
			if( Image::resolveExtension( it->entry.path() ) ){
				images.push_back(*it);
			}
		}
		// If there are at least noAngles indexed images, consider it a pegs dir.
		FileList::removeUnindexed(images);
		if(static_cast<int>(images.size())>=inputData.noAngles){
			// Get peg name
			std::string pegName;
			if(inputData.pegNamesStack.size()>0){
				pegName = inputData.pegNamesStack.front();
				inputData.pegNamesStack.pop_front();
			}
			else{
				pegName = dir.filename();
			}
			// Save the file list
			inputData.addPegFileList( PegFileList( images, FileInfo::parseFileNameIndex(dir.filename()),pegName) );
			return true;
		}
	}
	// If there is exactly 1 image, consider it a singlePeg image.
	else if(files.size()==1 && Image::resolveExtension(files.front().entry.path().extension()) ){
		// Get peg name
		std::string pegName;
		if(inputData.pegNamesStack.size()>0){
			pegName = inputData.pegNamesStack.front();
			inputData.pegNamesStack.pop_front();
		}
		else{
			pegName = dir.filename();
		}
		// Save data
		inputData.addPegFileList( PegFileList(files, FileInfo::parseFileNameIndex(dir.filename()), pegName ) );
		return true;
	}
	// Nothing was added to inputData.
	return false;
}

} // namespace GrobMaker
